#!/bin/bash

# ==========================================
# WASM 主构建脚本
# 自动发现并构建所有模块
# ==========================================

echo "=========================================="
echo "开始构建所有 WASM 模块..."
echo "=========================================="
echo ""

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# 创建输出目录
mkdir -p "$PROJECT_ROOT/dist/wasm"

# 计数器
SUCCESS_COUNT=0
FAIL_COUNT=0
SKIP_COUNT=0

# 查找所有模块的构建脚本
MODULE_SCRIPTS=$(find "$PROJECT_ROOT/src/modules" -type f -name "build.sh" 2>/dev/null)

if [ -z "$MODULE_SCRIPTS" ]; then
  echo "⚠️  未找到任何模块构建脚本"
  echo "   提示：在模块的 native/ 目录下创建 build.sh"
  exit 0
fi

# 遍历并执行每个模块的构建脚本
for SCRIPT in $MODULE_SCRIPTS; do
  MODULE_DIR=$(dirname "$SCRIPT")
  # 获取模块名称（macOS 兼容）
  MODULE_PATH=$(cd "$MODULE_DIR/.." && basename "$(pwd)")

  echo ">>> 构建模块: $MODULE_PATH"

  # 执行模块的构建脚本
  if bash "$SCRIPT"; then
    ((SUCCESS_COUNT++))
  else
    ((FAIL_COUNT++))
    echo "⚠️  模块 $MODULE_PATH 构建失败"
  fi

  echo ""
done

# 输出总结
echo "=========================================="
echo "WASM 构建完成"
echo "=========================================="
echo "✅ 成功: $SUCCESS_COUNT 个模块"
if [ $FAIL_COUNT -gt 0 ]; then
  echo "❌ 失败: $FAIL_COUNT 个模块"
fi
if [ $SKIP_COUNT -gt 0 ]; then
  echo "⏭️  跳过: $SKIP_COUNT 个模块"
fi
echo ""

# 列出构建产物
if [ -d "$PROJECT_ROOT/dist/wasm" ] && [ "$(ls -A $PROJECT_ROOT/dist/wasm 2>/dev/null)" ]; then
  echo "📦 构建产物:"
  ls -lh "$PROJECT_ROOT/dist/wasm/"*.wasm 2>/dev/null | awk '{print "   " $9 " (" $5 ")"}'
fi

# 如果有失败，退出码非0
if [ $FAIL_COUNT -gt 0 ]; then
  exit 1
fi
